package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.SpecValueMapper;
import com.zhentao.pojo.SpecGroup;
import com.zhentao.pojo.SpecValue;
import com.zhentao.service.SpecGroupService;
import com.zhentao.mapper.SpecGroupMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【spec_group(规格组表)】的数据库操作Service实现
* @createDate 2025-08-29 09:27:34
*/
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup>
    implements SpecGroupService{

    @Autowired
    private SpecValueMapper specValueMapper;

    @Override
    public List<SpecGroup> getProductSpecs(Integer productId) {
        List<SpecGroup> specGroups = list(new QueryWrapper<SpecGroup>().eq("product_id", productId));
        if (!specGroups.isEmpty()) {
            List<Long> groupIds = specGroups.stream().map(SpecGroup::getGroupId).toList();
            List<SpecValue> specValues = specValueMapper.selectList(new QueryWrapper<SpecValue>().in("group_id", groupIds));

            Map<Long, List<SpecValue>> valuesByGroup = specValues.stream()
                    .collect(Collectors.groupingBy(SpecValue::getGroupId));

            for (SpecGroup specGroup : specGroups) {
                specGroup.setSpecValues(valuesByGroup.getOrDefault(specGroup.getGroupId(), Collections.emptyList()));
            }
        }
        return specGroups;
    }

}




